package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.commons.contants.Contants;
import com.bjpowernode.crm.commons.domain.ReturnObject;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.commons.utils.HSSFUtils;
import com.bjpowernode.crm.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityRemarkService;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.bjpowernode.crm.workbench.utils.DownLoadUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Controller
public class ActivityController{
    @Autowired
    UserService userService;

    @Autowired
    ActivityService activityService;

    @Autowired
    ActivityRemarkService activityRemarkService;

    @RequestMapping(value = "/workbench/activity/index.do")
    public ModelAndView index(){
        ModelAndView md = new ModelAndView();
        List<User> userList = userService.queryAllUsers();
        md.addObject(userList);
        md.setViewName("workbench/activity/index");
        return md;
    }

    @RequestMapping(value = "/workbench/activity/saveCreateActivity.do")
    @ResponseBody
    public Object saveCreateActivity(Activity activity, HttpSession session){
        User user = (User)session.getAttribute(Contants.SESSION_USER);

        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDataTime(new Date()));
        activity.setCreateBy(user.getId());//外键引用主键

        ReturnObject retObj = new ReturnObject();

        try {
            int ret = activityService.saveCreateActivity(activity);

            if(ret > 0){
                //成功
                retObj.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            }else{
                //失败
                retObj.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                retObj.setMessage("系统繁忙,请稍后重试...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            retObj.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            retObj.setMessage("系统繁忙,请稍后重试...");
        }

        return retObj;
    }

    @RequestMapping(value = "/workbench/activity/queryActivityByConditionForPage.do")
    @ResponseBody
    public Object queryActivityByConditionForPage(String name,String owner,String startDate,String endDate,
                                                  int pageNo,int pageSize){
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("owner",owner);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("beginNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);

        List<Activity> activityList = activityService.queryActivityByConditionForPage(map);
        int totalRows = activityService.queryCountOfActivityByCondition(map);

        //根据查询结果,生成map
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("activityList",activityList);
        resultMap.put("totalRows",totalRows);

        return resultMap;
    }

    @RequestMapping(value = "/workbench/activity/deleteActivityByIds.do")
    @ResponseBody
    public Object deleteActivityByIds(String[] ids){
        ReturnObject returnObject = new ReturnObject();

        try {
            int num = activityService.deleteActivityByIds(ids);
            if(num > 0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统繁忙,请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,请稍后重试");
        }

        return returnObject;
    }

    @RequestMapping(value = "/workbench/activity/queryActivityById.do")
    @ResponseBody
    public Object queryActivityById(String id){
        ReturnObject returnObject = new ReturnObject();

        try {
            Activity activity = activityService.queryActivityById(id);
            if(activity == null){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统繁忙,请稍后再试");
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(activity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,请稍后再试");
        }

        return returnObject;
    }

    @RequestMapping(value = "/workbench/activity/updateActivityById.do")
    @ResponseBody
    public Object updateActivityById(Activity activity,HttpSession session){
        User user = (User)session.getAttribute(Contants.SESSION_USER);
        activity.setEditTime(DateUtils.formatDataTime(new Date()));
        activity.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();

        try {
            int res = activityService.updateActivityById(activity);
            if(res > 0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统繁忙,请稍后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,请稍后再试");
        }

        return returnObject;
    }

    @RequestMapping(value = "/workbench/activity/downloadAllActivity.do")
    public void downloadAllActivity(HttpServletRequest request, HttpServletResponse response){
        List<Activity> activityList = null;
        try {
            activityList = activityService.queryAllActivity();
            DownLoadUtils.downloadActivity(activityList,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/workbench/activity/downloadActivityByIds.do")
    public void downloadActivityByIds(String[] ids,HttpServletResponse response){
        List<Activity> activityList = null;

        try {
            activityList = activityService.queryActivityByIds(ids);
            DownLoadUtils.downloadActivity(activityList,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/workbench/activity/fileupload.do")
    @ResponseBody
    public Object fileupload(MultipartFile activityFile,HttpSession session){

        String path = session.getServletContext().getRealPath("/xls/") + activityFile.getOriginalFilename();
        User user = (User)session.getAttribute(Contants.SESSION_USER);

        ReturnObject returnObject = new ReturnObject();

        try {
            //activityFile.transferTo(new File(path));

            //FileInputStream is = new FileInputStream(path);
            HSSFWorkbook workbook = new HSSFWorkbook(activityFile.getInputStream());

            HSSFSheet sheet = workbook.getSheetAt(0);

            List<Activity> activityList = new ArrayList<>();
            Activity activity=null;
            HSSFRow row;
            HSSFCell cell;
            int j = 0;
            for(int i = 1;i <= sheet.getLastRowNum();i++){
                row = sheet.getRow(i);
                activity = new Activity();
                activity.setId(UUIDUtils.getUUID());
                activity.setOwner(user.getId());
                activity.setCreateTime(DateUtils.formatDataTime(new Date()));
                activity.setCreateBy(user.getId());
                for(j = 0;j < row.getLastCellNum();j++){
                    cell = row.getCell(j);
                    String cellValue = HSSFUtils.getCellValue(cell);
                    if(j == 0){
                        activity.setName(cellValue);
                    }else if(j == 1){
                        activity.setStartDate(cellValue);
                    }else if(j == 2){
                        activity.setEndDate(cellValue);
                    }else if(j == 3){
                        activity.setCost(cellValue);
                    }else if(j == 4){
                        activity.setDescription(cellValue);
                    }
                }
                activityList.add(activity);
            }

            int res = activityService.saveCreateActivityByList(activityList);

            if(res > 0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(res);
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统繁忙,请稍后再试");
            }

        } catch (IOException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,请稍后再试");
        }

        return returnObject;
    }

    @RequestMapping(value = "/workbench/activity/detailActivity.do")
    public String detailActivity(String id,HttpServletRequest request){
        try {
            Activity activity = activityService.queryActivityByIdForDetail(id);
            List<ActivityRemark> activityRemarkList = activityRemarkService.queryAllActivityRemarkByActivityId(id);
            if(activity!=null){
                request.setAttribute("id",activity.getId());
                request.setAttribute("owner",activity.getOwner());
                request.setAttribute("name",activity.getName());
                request.setAttribute("startDate",activity.getStartDate());
                request.setAttribute("endDate",activity.getEndDate());
                request.setAttribute("cost",activity.getCost());
                request.setAttribute("description",activity.getDescription());
                request.setAttribute("createTime",activity.getCreateTime());
                request.setAttribute("createBy",activity.getCreateBy());
                request.setAttribute("editTime",activity.getEditTime());
                request.setAttribute("editBy",activity.getEditBy());
            }

            request.setAttribute("activityRemarkList",activityRemarkList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "workbench/activity/detail";
    }
}
